package ProducerConsumer;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicReference;

public class BlockqueueImpl01 {
    public static void main(String[] args) {
        BlockingQueue<Cup> queue = new ArrayBlockingQueue<>(10);
        AtomicReference<Integer> index = new AtomicReference<>(0);

        Runnable producer = () -> {
            while (true) {
                try {
                    Integer t = index.get() + 1;
                    System.out.println("Try to produce Cup:" + t);
                    Thread.sleep(500);
                    queue.put(new Cup(index.getAndSet(index.get() + 1)));
                    System.out.println("Finished producing Cup: " + t);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        new Thread(producer).start();
        new Thread(producer).start();

        Runnable consumer = () -> {
            while (true) {
                try {
                    Thread.sleep(400);
                    Cup cup = queue.take();
                    System.out.println("Consumed cup: " + cup);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        new Thread(consumer).start();
        new Thread(consumer).start();

    }
}
